import 'package:dio/dio.dart';
import 'package:dio/io.dart';
import 'package:http_mock_adapter/http_mock_adapter.dart';

import '../config/env_config.dart';
import '../core/network_interceptor.dart';
import '../core/network_provider.dart';
import '../core/network_request.dart';

class NetworkMock extends NetworkInterceptor {
  @override
  int get priority => 1;

  @override
  void willSend(RequestOptions options, RequestInterceptorHandler handler,
      TargetType target) {
    if (HMNetworkConfig.openMock && target.mockData != null) {
      final mock = target.mockData!;
      DioAdapter(
        dio: NetworkProvider.shared.provider,
        matcher: const UrlRequestMatcher(),
      ).onRoute(
        target.fullPath(),
        (server) => server.reply(
          mock.statusCode,
          mock.data,
          delay: mock.delay,
        ),
        request: Request(
          route: target.fullPath(),
          method: _mapMethod(target.method),
          data: options.data,
          queryParameters: options.queryParameters,
          headers: options.headers,
        ),
      );
    } else {
      NetworkProvider.shared.provider.httpClientAdapter = IOHttpClientAdapter();
    }
    super.willSend(options, handler, target);
  }

  _mapMethod(Method method) =>
      RequestMethods.forName(name: method.name.toUpperCase());
}
